package com.ruo;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


public class urlEncode {

    public static String genParamsStr(Map<String, String> params) {
        if (params.isEmpty()) {
            return "";
        }

        StringBuilder builder = new StringBuilder();
        builder.append("?");
        Set<String> keys = params.keySet();
        Iterator<String> iterKey = keys.iterator();
        String firstKey = iterKey.next();
        builder.append(firstKey + "=" + params.get(firstKey));

        while (iterKey.hasNext()) {
            String key = iterKey.next();
            String value = params.get(key);
            String valueEncoded = "";
            try {
                valueEncoded = URLEncoder.encode(value, "UTF-8");
            } catch (Exception e) {
                System.out.println("error when url encode order url");
            }
            builder.append("&" + key + "=" + valueEncoded);
        }
        return builder.toString();
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
//        Map<String, String> params = new HashMap<>();
//        params.put("abc","47863");
//        System.out.println(urlEncode.genParamsStr(params));

        String abc="超牛+套餐-39元套餐(山东)";
        String s = URLEncoder.encode(abc, "UTF-8");
        String q = "random word 拢500 bank $";
        String url = "http://example.com/query?q=" + URLEncoder.encode(q, "UTF-8");


        String param = URLDecoder.decode(url, "utf-8");
        String param1 = URLDecoder.decode(s, "utf-8");

        System.out.println(url);
        System.out.println(param);

        System.out.println("----------------");

        System.out.println(s);
        System.out.println(param1);
    }


}
